<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>添加文章</title>
    <link rel="stylesheet" href="/static/css/bulma.min.css" th:href="@{/css/bulma.min.css}">
    <link rel="stylesheet" href="/static/css/community.css" th:href="@{/css/community.css}">
    <link rel="stylesheet" href="/static/css/article-tag.css" th:href="@{/css/article-tag.css}">
    <link rel="stylesheet" href="/static/wangEditor/css/style.css" th:href="@{/wangEditor/css/style.css}">
    <link rel="stylesheet" href="/css/msg.css" th:href="@{/css/msg.css}">
    <link rel="stylesheet" href="/static/css/panel-tag.css" th:href="@{/css/panel-tag.css}">
    <link rel="stylesheet" href="/static/css/notice.css" th:href="@{/css/notice.css}">
    <script type="text/javascript" src="/static/wangEditor/js/index.js" th:src="@{/wangEditor/js/index.js}"></script>
    <script type="text/javascript" src="/static/js/jquery-3.7.1.min.js" th:src="@{/js/jquery-3.7.1.min.js}"></script>
    <script type="text/javascript" src="/static/js/awesome.js" th:src="@{/js/awesome.js}"></script>
    <!--    <script type="text/javascript" src="/static/js/article-tag.js" th:src="@{/js/article-tag.js}"></script>-->
    <script type="text/javascript" src="/static/js/community.js" th:src="@{/js/community.js}"></script>
    <script type="text/javascript" src="/static/js/panel-tag.js" th:src="@{/js/panel-tag.js}"></script>
    <script type="text/javascript" src="/js/msg.js" th:src="@{/js/msg.js}"></script>
    <script type="text/javascript" src="/static/js/notice.js" th:src="@{/js/notice.js}"></script>
</head>
<body class="has-navbar-fixed-top">
<!-- 导航栏内容 -->
<div th:replace="~{common/nav::nav(current=1,size=10,keyword='')}"></div>
<!-- 中间部分内容 -->
<section class="section">
    <!-- 错误提示飘窗 -->
    <div id="toast" class="notification is-danger">
        错误信息：操作失败，请稍后再试。
    </div>
    <div class="container is-max-widescreen ">
        <div class="columns is-desktop index-top">
            <div class="column is-1"></div>
            <div class="column is-10">
                <div class="card index-card-border">
                    <header class="card-header-title article-card-header level">
                        <span class="level-left">
                            <span class="level-item ">
                                添加文章
                            </span>
                        </span>
                        <span class="level-right ">
                            <a href="#" th:href="@{/article/list}" class="is-rounded is-outlined is-dark button level-item">
                                <i class="fa-solid fa-list"></i> &nbsp;
                                我的帖子
                            </a>
                        </span>
                    </header>
                    <div class="divider"></div>
                    <div class="card-content">
                        <div class="field">
                            <label class="label">标题</label>
                            <div class="control">
                                <input id="title-btn" class="input" type="text" name="title"
                                       th:value="${detail==null?null:detail.title}"
                                       placeholder="请输入文章标题...">
                            </div>
                        </div>

                        <div class="field">
                            <label class="label">正文</label>
                            <div class="control">
                                <div id="editor—wrapper">
                                    <div id="toolbar-container"><!-- 工具栏 --></div>
                                    <div id="editor-container"><!-- 编辑器 --></div>
                                </div>
                            </div>
                        </div>


                        <div class="field">
                            <label class="label">标签</label>
                            <div class="control">
                                <div>
                                    <div id="input-tags" contenteditable="true">

                                    </div>
                                    <div style="margin-top:10px">
                                        <span th:each="tagParent,stat:${detail.tagParents}"
                                              th:class="${stat.index==0?'tag-parent tag-click-item':'tag-parent'}"
                                              th:data-id="${'tag-parent-id-'+tagParent.id}"
                                              th:text="${'#'+tagParent.name}"
                                              class="tag-parent tag-click-item"
                                              data-id="tag-parent-id-1">
                                            # 搞笑
                                        </span>
                                     <!--   <span class="tag-parent" data-id="tag-parent-id-2">
                                            # 生活

                                        </span>-->
                                    </div>
                                    <div class="divider"></div>
                                    <div class="tag-child-show tag-child-border"  data-parent-id="tag-parent-id-1"
                                         th:each="tagParent:${detail.tagParents}" th:data-parent-id="${'tag-parent-id-'+tagParent.id}">
                                        <span th:each="tag:${tagParent.tags}"
                                              th:data-id="${tag.id}"
                                              th:data-tag-id="${'tag-parent-id-'+tagParent.id+'-'+tag.id}"
                                              th:class="${tag.selected?'is-info is-focused button is-small tag-child':'button is-small tag-child'}"
                                              th:text="${tag.name}"
                                              data-id="1"  data-tag-id="tag-parent-id-1-1"
                                              class="button is-small tag-child  ">经济</span>
                                    </div>
                                </div>
                                <div id="tag-limit-message"></div>

                                <!--<div>
                                    &lt;!&ndash; 上方标签区域 &ndash;&gt;
                                    <div class="warning-text" id="warning-text">
                                        当前文章选中的标签(如下),可手动输入
                                    </div>
                                    <div class="tag-container" id="tag-container">
                                        &lt;!&ndash; 标签按钮显示区域 &ndash;&gt;
                                    </div>

                                    &lt;!&ndash; 下方输入框区域（Bulma输入框样式） &ndash;&gt;
                                    <div class="tag-input-container">
                                        <input class="input" type="text" id="tag-input"
                                               placeholder="输入标签，按 “回车” 或 “/” 来创建标签">
                                        <div class="error-message" id="error-message"></div>
                                    </div>
                                </div>-->


                                <!--<div id="error-message" class="error-message" style="display:none;"></div>

                                <div class="custom-select-wrapper">
                                    <div class="custom-select" id="selectBox">
                                        <div class="selected-container">
                                            &lt;!&ndash; 选择的元素将会在这里展示 &ndash;&gt;
                                        </div>
                                    </div>
                                    <button class="toggle-button" id="toggleButton">选择元素</button>
                                </div>
                                <div class="select-dropdown" id="selectDropdown">
                                    <div class="option" value="SpringBoot">SpringBoot</div>
                                    <div class="option" value="SpringMVC">SpringMVC</div>
                                    <div class="option" value="MyBatis">MyBatis</div>
                                    <div class="option" value="SpringWebFlux">SpringWebFlux</div>
                                    <div class="option" value="Spring">Spring</div>
                                    <div class="option" value="Redis">Redis</div>
                                    <div class="option" value="Mysql">Mysql</div>
                                    <div class="option" value="SpringBoot2">SpringBoot2</div>
                                    <div class="option" value="SpringMVC2">SpringMVC2</div>
                                    <div class="option" value="MyBatis2">MyBatis2</div>
                                    <div class="option" value="SpringWebFlux2">SpringWebFlux2</div>
                                    <div class="option" value="Spring2">Spring2</div>
                                    <div class="option" value="Redis2">Redis2</div>
                                    <div class="option" value="Mysql2">Mysql2</div>
                                </div>-->
                            </div>

                        </div>

                        <div class="field">
                            <label class="label">上传首图</label>
                            <div class="file">
                                <label class="file-label">
                                    <input id="file-btn" class="file-input" type="file" name="file"/>
                                    <span class="file-cta">
                                      <span class="file-icon">
                                        <i class="fas fa-upload"></i>
                                      </span>
                                      <span class="file-label"> 上传文件 </span>
                                    </span>
                                </label>
                            </div>
                            <!-- 图片显示区域 -->
                            <div id="img-container"class="image-preview image-container" style="position: relative">
                                <img id="image-preview" th:src="${detail.firstPicture}"
                                     src="/static/img/000.jpg" alt="">
                                <span id="remove-icon" class="delete-tag">
                                    <i class="fa-solid fa-trash"></i>
                                </span>
                            </div>
                        </div>

                        <div class="field btn-article-other">
                            <div class="checkboxes">
                                <label class="checkbox">
                                    <input type="checkbox" id="comment-btn"
                                           th:checked="${detail.commentable==null?true:detail.commentable}" checked/>
                                    评论
                                </label>

                                <label class="checkbox">
                                    <input type="checkbox" id="recommend-btn"
                                           th:checked="${detail.recommend==null?true:detail.recommend}" checked/>
                                    推荐
                                </label>

                                <label class="checkbox">
                                    <input type="checkbox" id="appreciation-btn"
                                           th:checked="${detail.appreciation==null?false:detail.appreciation}"/>
                                    赞赏
                                </label>

                                <label class="checkbox">
                                    <input type="checkbox" id="share-btn"
                                           th:checked="${detail.shareable==null?false:detail.shareable}"/>
                                    分享
                                </label>

                            </div>
                        </div>


                        <div class="btn-is-right">
                            <div class="control">
                                <button id="add-btn" th:data-id="${detail.id==null?0:detail.id}"
                                        class="button is-link is-info">提交
                                </button>
                            </div>
                            <div class="control">
                                <a th:href="@{/article/list}" id="close-btn" class="button is-link is-light">关闭</a>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
            <div class="column is-1"></div>
        </div>
    </div>
</section>
<!-- 底部部分内容 -->
<div th:replace="~{common/footer::footer}"></div>
<script type="application/javascript" th:inline="javascript">
    $(window).on('load',function (){
        $(document).ready(function () {
            $("#file-btn").change(function (event) {
                console.log("上传文件触发了....") // TODO 应该判断下是不是图片
                var file = event.target.files[0];
                if (file) {
                    var formData = new FormData();
                    formData.append('file', file);
                    $.ajax({
                        url: "/file/upload",
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            console.log("文件上传后返回结果:" + res)
                            $("#image-preview").attr("src", res.data.url)
                            toggleDeleteButton();
                            // 上传成功后重置文件输入控件
                            $("#file-btn").val('');
                        },
                        error: function (err) {
                            showErrorToast("文件上传失败")
                        }
                    })
                }
            })
        });

        toggleDeleteButton();

        $("#remove-icon").click(function (){
            console.log("删除图片....")
            $('#image-preview').attr('src', '');
            toggleDeleteButton();
        })

        // 显示或隐藏删除按钮
        function toggleDeleteButton() {
            var imageSrc = $('#image-preview').attr('src');
            if (imageSrc === '') {
                $("#img-container").hide();  // 图片为空时隐藏删除按钮
            } else {
                $("#img-container").show();  // 图片存在时显示删除按钮
            }
        }

        const {createEditor, createToolbar} = window.wangEditor

        const editorConfig = {
            placeholder: '写点什么吧...',
            scroll: true,
            MENU_CONF: {},
            onChange(editor) {
                const html = editor.getHtml()
                console.log('editor content', html)
                // 也可以同步到 <textarea>
            }
        }

        editorConfig.MENU_CONF['uploadImage'] = {
            // 自定义上传
            async customUpload(file, insertFn) {
                console.log('自定义上传图片.....', file)
                var formData = new FormData();
                formData.append('file', file);
                $.ajax({
                    url: "/file/upload",
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        console.log("文件上传后返回结果:" + res)
                        insertFn(res.data.url, res.data.newName, res.data.url)
                    },
                    error: function (err) {
                        showErrorToast("文件上传失败")
                    }
                })
            }
        }

        editorConfig.MENU_CONF['uploadVideo'] = {
            async customUpload(file, insertFn) {
                console.log('自定义上传视频.....', file)
                var formData = new FormData();
                formData.append('video', file);
                $.ajax({
                    url: "/file/upload/video",
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        console.log("文件上传后返回结果:" + res)
                        insertFn(res.data.url, res.data.poster)
                    },
                    error: function (err) {
                        showErrorToast("文件上传失败")
                    }
                })
            }
        }

        // TODO 怎么没有java语言选择
        const editor = createEditor({
            selector: '#editor-container',
            html: '',
            config: editorConfig,
            mode: 'default', // or 'simple'
        })

        const toolbarConfig = {}

        const toolbar = createToolbar({
            editor,
            selector: '#toolbar-container',
            config: toolbarConfig,
            mode: 'default', // or 'simple'
        })

        $("#add-btn").click(function () {
            var articleId = $("#add-btn").data("id");
            var title = $("#title-btn").val();
            var html = editor.getHtml();
            var imgSrc = $('#image-preview').attr('src');
            var commentChecked = $('#comment-btn').prop('checked');
            var recommendChecked = $('#recommend-btn').prop('checked');
            var appreciationChecked = $('#appreciation-btn').prop('checked');
            var shareChecked = $('#share-btn').prop('checked');
            var tagIds = [];
            $('#input-tags .tag-child-selector').each(function () {
                // 获取 data-id 属性值并添加到数组中
                tagIds.push($(this).data('id'));
            });

            if (tagIds.length === 0) {
                $("#tag-limit-message").text("标签不能为空").css("color", "red");
                return;
            }

            var url = articleId === 0 ? '/article' : `/article/${articleId}`
            var method = articleId === 0 ? 'POST' : 'PUT'
            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify({
                    'title': title,
                    'content': html,
                    'firstPicture': imgSrc,
                    'tagIds':tagIds,
                    'commentable': commentChecked,
                    'recommend': recommendChecked,
                    'appreciation': appreciationChecked,
                    'shareable':shareChecked
                }),
                success: function (res) {
                    if (res.code === 200) {
                        console.log(res.data.id);
                        // 实现跳转，例如：
                        window.location.href = '/article/list';
                    } else {
                        showErrorToast(res.msg);
                    }
                },
                error: function (err) {
                    // 确保错误处理与服务器响应结构相匹配
                    showErrorToast(err);
                }
            });

        })


        let editTags = [];
        var content = [[${detail.content}]]
        if (content !=null) {
            console.log("content:" + content)
            editor.setHtml(content)
            editTags = [[${detail.tags}]]
            editTags.map(item =>{
                window.selectedTags.push(item.name)
                var spanElement = $("<span>")
                    .addClass("button is-small is-light tag-child-selector")
                    .attr("data-tag-id", 'tag-parent-id-'+item.parentId+'-'+item.id)
                    .attr("data-id",item.id)
                    .text(item.name);
                var deleteButton = $("<span>").addClass("tag-remove-icon").text("X");
                spanElement.append(deleteButton);
                $("#input-tags").append(spanElement);
            })
        }
    })

</script>
</body>

<style>

    #editor—wrapper {
        border: 1px solid #ccc;
        z-index: 100; /* 按需定义 */
    }

    #toolbar-container {
        border-bottom: 1px solid #ccc;
    }

    #editor-container {
        height: 400px;
    }
</style>
</html>